package com.diandian.backend.jingdong.home.exchange.service;

import com.diandian.jingdong.home.boot.starter.constants.JingdongHomeConstant;
import com.diandian.jingdong.home.boot.starter.service.token.JingdongTokenBasicService;
import com.diandian.jingdong.home.boot.starter.service.token.dto.TokenRequestDTO;
import com.diandian.jingdong.home.boot.starter.service.token.dto.TokenResponseDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class BusinessJingdongTokenService {

    private static final Logger logger = LoggerFactory.getLogger(BusinessJingdongTokenService.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JingdongTokenBasicService service;

    /**
     * token有效期expire值为12个月（30天）的秒值，即31104000=12*30*24*60*60
     *
     * 参考文档：
     *      https://opendj.jd.com/staticnew/widgets/resources.html?id=2014
     *      https://opendj.jd.com/staticnew/widgets/resources.html?id=2022
     * @param dto token数据对象
     * @param appKey
     * @param appSecret
     * @return
     * @throws Exception
     */
    public TokenResponseDTO acceptTokenInfo(TokenRequestDTO dto, String appKey, String appSecret) throws Exception {

        logger.info("接收到京东TOKEN数据: " + dto);

        if (dto == null || dto.getToken() == null || "".equals(dto.getToken())) {
            return new TokenResponseDTO("1", "fail", "");
        }
        String newToken = dto.getToken();

        // 更新缓存中的token
        redisTemplate.opsForValue().set(JingdongHomeConstant.REDIS_TOKEN_KEY + appKey, newToken);
        logger.info("更新缓存数据完成，TOKEN: " + dto.getToken());

        // 向京东到家发送token确认请求
        service.confirmToken(getToken(appKey), newToken, appKey, appSecret);

        return new TokenResponseDTO("0", "success", "");
    }

    /**
     * 从缓存中获取token
     * @return
     */
    public String getToken(String appKey) {
        Object tokenObject = redisTemplate.opsForValue().get(JingdongHomeConstant.REDIS_TOKEN_KEY + appKey);
        return tokenObject == null ? "" : String.valueOf(tokenObject);
    }
}
